package MyGui;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.util.zip.*;
import javax.jnlp.*;

import DistSys.*;
import DataAccess.DBAccessor;
import DataAccess.Storage.PersonalInfoForStorage;

public class MainFrame extends JFrame implements WindowListener{
    MainApplet theApplet = null;
    File fileIni;

    JScrollPane  scrollPane;
    DrawingPanel mainPanel;
    ButtonPanel  btnPanel;
    MainMenuBar  menuBar;
    MyPopupMenu  popupMenu;
    MyPopupMenu2  popupMenu2;
    StatusPanel  statusBar;

    public static void main(String[] arg) {
        try {
            // Use systems look & feel for the first windows
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

            MainFrame frame = new MainFrame(arg.length >= 1 ? arg[0] : null);
            // no applet as application
            frame.setApplet(null);
            // NOTE: Since this method is static we are not allowed to declare
            // variables of the type javax.jnlp.BasicService or
            // javax.jnlp.UnavailableServiceException because both classes are
            // not available when started as an applet.
            try {
                WebConst.setWebPath(((BasicService)ServiceManager.
                    lookup("javax.jnlp.BasicService")).
                    getCodeBase().toString());
            } catch (Exception e) {
                if (SysConst.DEBUG_MODE == 0 &&
                    e instanceof UnavailableServiceException) {
                    // NOTE: It is likely that we started iPAD from JBuilder
                    // when we encounter this exception in debug mode. In that
                    // case we don't want a message dialog.
                    JOptionPane.showMessageDialog(null, e);
                }
            }
        } catch(Exception e) {
            JOptionPane.showMessageDialog(null, e); //e.printStackTrace();
        }
    }

    public MainFrame(String sFilename) {
        // get personal info
        try {
            fileIni = new File(System.getProperty("user.home"), "iPad.ini");
            if (fileIni.exists() && fileIni.canRead()) {
                ZipInputStream zin = new ZipInputStream(new FileInputStream(
                    fileIni));
                zin.getNextEntry();
                ObjectInputStream ois = new ObjectInputStream(zin);

                String sIpadVersion = (String ) ois.readObject(); // not used now
                PersonalInfoForStorage pifs = (PersonalInfoForStorage)ois.readObject();
                Sys.personalInfo = pifs.createPersonalInfoFromThis();

                zin.closeEntry();
                zin.close();
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                "An error occured while loading the personal settings.");
            Sys.personalInfo = null;
        }
        if (Sys.personalInfo == null) {
            // set hopefully reasonable default values
            Sys.personalInfo = new PersonalInfo();
            // show paths dialog to verify paths
            final JDialog dlg = new JDialog((Frame)null, "Choose paths", true);
            dlg.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
            dlg.setLocation(200,200);
            dlg.setSize(450, 232);

            Container contentPane = dlg.getContentPane();
            contentPane.setLayout(new BorderLayout());

            final OptionsDlg.PathsPanel pathsPanel = new OptionsDlg.PathsPanel();
            contentPane.add(pathsPanel, BorderLayout.CENTER);

            JPanel buttonPanel = new JPanel();
            contentPane.add(buttonPanel, BorderLayout.SOUTH);
            JButton btnOk = new JButton("Ok");
            buttonPanel.add(btnOk);
            dlg.getRootPane().setDefaultButton(btnOk);

            btnOk.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    pathsPanel.save();
                    dlg.dispose();
                }
            });
            dlg.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent evt) {
                    pathsPanel.save();
                }
            });

            dlg.show();
        }

        try {
            UIManager.setLookAndFeel(
                Sys.personalInfo.getLookAndFeelClassName());
        } catch(Exception e) {
            JOptionPane.showMessageDialog(null, "The selected Look&Feel " +
                "was not found, using system default instead.", "Error",
                JOptionPane.ERROR_MESSAGE);
        }

        setIconImage(GuiConst.ipadIcon.getImage());

        menuBar = new MainMenuBar();
        setJMenuBar(menuBar);

        popupMenu = new MyPopupMenu(this);
        popupMenu2 = new MyPopupMenu2(this);

        Container contentPane = getContentPane();
        contentPane.setLayout(new BorderLayout());

        btnPanel = new ButtonPanel();
        contentPane.add(btnPanel, BorderLayout.NORTH);

        mainPanel = new DrawingPanel();
        scrollPane = new JScrollPane(mainPanel);
        scrollPane.getViewport().setViewPosition(new Point(
            mainPanel.INIT_VIEW_WIDTH/2, mainPanel.INIT_VIEW_HEIGHT/2));
        // set unit increment for slider
        scrollPane.getVerticalScrollBar().setUnitIncrement(20);
        scrollPane.getHorizontalScrollBar().setUnitIncrement(20);
        // repaint after any scrolling
        scrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE);
        contentPane.add(scrollPane, BorderLayout.CENTER);

        statusBar = new StatusPanel();
        contentPane.add(statusBar, BorderLayout.SOUTH);

        mainPanel.mainFrame = this;
        btnPanel.mainFrame  = this;
        menuBar.mainFrame   = this;
        statusBar.mainFrame = this;

        Sys.mainFrame = this;
        DBAccessor.mainFrame = this;

        addWindowListener(this);
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        //addComponentListener(this);

        // We need to set the size and visibility here. Otherwise the zoomAll
        // call inside openProject later on will not work correctly.
        setLocation(150,150);
        setSize(800,600);
        setVisible(true);

        if (sFilename != null && sFilename.length() > 0) {
            // replace all "%20" in the file name with real whitespaces
            final String sSpace = "%20";
            int index = sFilename.indexOf(sSpace);
            if (index >= 0) {
                StringBuffer sBuffer = new StringBuffer(sFilename.length());
                int indexAfter = 0;
                do {
                    // append string between "%20"s
                    sBuffer.append(sFilename.substring(indexAfter, index));
                    // append real white space
                    sBuffer.append(' ');
                    // skip "%20" in file name
                    indexAfter = index + sSpace.length();
                    // is there another "%20"?
                    index = sFilename.indexOf(sSpace, indexAfter);
                } while (index >= 0);
                // append the remaining string
                sBuffer.append(sFilename.substring(indexAfter));
                sFilename = sBuffer.toString();
            }
            // trim filename
            sFilename = sFilename.trim();
            // start with this project
            File fFile = new File(sFilename);
            if (!fFile.exists()) {
                // file does not exist, report and start with new project
                JOptionPane.showMessageDialog(null, "'" + sFilename +
                    "' does not exist.", "Error", JOptionPane.ERROR_MESSAGE);
                menuBar.newProject();
            } else if (!menuBar.openProject(fFile)) {
                // open failed, start with new project
                menuBar.newProject();
            }
        } else {
            // start with new project
            menuBar.newProject();
        }
    }

    public void done() {
        // save personal info
        try {
            ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(
                fileIni));
            zout.putNextEntry(new ZipEntry("iPad.PersonalSettings"));
            ObjectOutputStream oos = new ObjectOutputStream(zout);

            String sIpadVersion = Sys.prjInfo.sVersion;
            oos.writeObject( sIpadVersion); // reserved; not used now
            PersonalInfoForStorage pifs = new PersonalInfoForStorage();
            pifs.copyFromPersonalInfo( Sys.personalInfo );
            oos.writeObject( pifs );

            zout.closeEntry();
            zout.close();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                "An error occured while saving the personal settings.");
        }
        if (!Sys.personalInfo.deleteTempFiles()) {
            JOptionPane.showMessageDialog(null,
                "An error occured while deleting the temporary files.");
        }
    }

    /*======================================
      Implement WindowListener interfaces
      ======================================*/
    public void windowOpened( WindowEvent evt ){ }
    public void windowClosed( WindowEvent evt ){ }
    public void windowIconified( WindowEvent evt ){ }
    public void windowDeiconified( WindowEvent evt ){ }
    public void windowActivated( WindowEvent evt ){ }
    public void windowDeactivated( WindowEvent evt ){ }
    public void windowClosing( WindowEvent evt ){
        this.menuBar.alExit.actionPerformed(null);
    }

    public DrawingPanel getMainPanel() { return mainPanel; }
    public MainMenuBar getMainMenuBar() { return menuBar; }

    public void setApplet( MainApplet ma ) { theApplet = ma; }
    public MainApplet getApplet() { return theApplet; }

    public boolean showDocument(String sURL, String target)
        throws MalformedURLException, UnavailableServiceException {
        URL url = new URL(sURL);
        if (theApplet != null) {
            theApplet.getAppletContext().showDocument(url, target);
            return true;
        } else {
            BasicService bs = (BasicService)ServiceManager.
                lookup("javax.jnlp.BasicService");
            return bs.showDocument(url);
        }
    }


 /* public void componentHidden(ComponentEvent evt){}
  public void componentShown(ComponentEvent evt){}
  public void componentMoved(ComponentEvent evt){
      Point pt = this.scrollPane.getViewport().getViewPosition();
      //Point pt= new Point(Sys.prevViewPosition);
      this.mainPanel.updateViewSize( pt);
      this.scrollPane.getViewport().setViewPosition(pt);//new Point(newRect.x, newRect.y) );
      this.mainPanel.repaint();
  }
  public void componentResized(ComponentEvent evt){
      Point pt = this.scrollPane.getViewport().getViewPosition();
      //Point pt= new Point(Sys.prevViewPosition);
      this.mainPanel.updateViewSize( pt);
      System.out.println("OOOOOO:"+pt);
      this.scrollPane.getViewport().setViewPosition(pt);//new Point(newRect.x, newRect.y) );
      this.mainPanel.repaint();
  }*/
}